package com.william.springsecurity.filter;

import com.william.springsecurity.common.Constant;
import com.william.springsecurity.exception.CaptchaException;
import com.william.springsecurity.handler.LoginFailureHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

// 验证码过滤器
@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = httpServletRequest.getRequestURI();
        if(Objects.equals(requestURI,"/login") && Objects.equals(httpServletRequest.getMethod(),"POST")){
            // 校验验证码
            try {
                validate(httpServletRequest);
            } catch (CaptchaException e) {
                // 转交认证处理器
                loginFailureHandler.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
            }
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }

    // 校验验证码
    private void validate(HttpServletRequest httpServletRequest) throws CaptchaException {
        // 验证码
        String code = httpServletRequest.getParameter("code");
        String key = httpServletRequest.getParameter("key");
        if(StringUtils.isBlank(code)){
            throw new CaptchaException("验证码错误");
        }
        if(StringUtils.isBlank(key)){
            throw new CaptchaException("Token为空");
        }
        String redisCode = (String) redisTemplate.opsForHash().get(Constant.CAPTCHA, key);
        redisCode = "123";
        if(!Objects.equals(redisCode,code)){
            throw new CaptchaException("验证码错误");
        }
        // 删除验证码
//        redisTemplate.opsForHash().delete(Constant.CAPTCHA, key);

    }
}
